﻿var konsolAntresol = konsolAntresol || {};

(function ($, ka) {

	ka.view = {
		$calcContainer: null,
		$calcPopupContainer: null,
		$headMenuContainer: null,
		$galleryContainer: null
	};

	ka.viewmodel = {

	};

	$.extend(ka, {
		init: function() {
			this.setDomOptions();
			this.bindEvents();
			this.processingGallery();
			this.initImageBox();
		},

		bindEvents: function() {
			var context = this,
				view = ka.view;
			view.$calcContainer.find('.calcImage')
				.add(view.$calcContainer.find('.calcInfo span'))
				.off('click').on('click', function() {
					context.showCalcPopup();
				});

			view.$headMenuContainer.find('.menuItem > a').on('mouseenter', function() {
				var $menuItem = $(this),
					$subMenu = $menuItem.closest('.menuItem').find('ul');
				if ($subMenu) {
					$subMenu.css('left', $menuItem.position().left)
						.show()
						.on('mouseenter', function() {
							$subMenu.show();
						})
						.add($menuItem)
						.on('mouseleave', function() {
							$subMenu.hide();
						});
				}
			});
		},

		setDomOptions: function() {
			var view = ka.view;
			view.$calcContainer = $('#calcContainer');
			view.$calcPopupContainer = $('#calcPopupContainer');
			view.$headMenuContainer = $('#headMenuContainer');
			view.$galleryContainer = $('#galleryContainer');
		},

		getImages: function() {
			var url = "/Home/GetGalleryImages";
			return $.ajax({
				method: 'GET',
				dataType: 'json',
				contentType: 'application/json; chrset=utf8',
				url: url,
				error: function(error) {
					console.log(error);
				}
			});
		},

		processingGallery: function() {
			var context = this;
			$.when(this.getImages())
				.done(function(images) {
					context.renderImages(images);
					ka.view.$galleryContainer.find('img').off('load').on('load', function() {
						context.runCarousel();
					});

				});
		},

		renderImages: function (images) {
			var template = '{{each images}}<img id="image_${$index + 1}" style="display: none; height: 593px; width: 960px;" src=${$value} />{{/each}}';
			$.template('imagesTemplate', template);
			ka.view.$galleryContainer.append($.tmpl('imagesTemplate', { images: images }));
		},

		runCarousel: function() {
			var $galleryContainer = $('#galleryContainer'),
				$images = $galleryContainer.find('img'),
				count = $images.length;
				$images.off('load');
			$images.first().show();
			var carousel = function(index) {
				var $img = $('#image_' + index);
				if (++index > count) {
					index = 1;
				}
				$('#image_' + index).fadeIn(2000, function() {
						$img.hide();
						carousel(index);
				});
			};
			carousel(1);
		}
	});

})(jQuery, konsolAntresol);